import type {Router, RouteRecordRaw} from 'vue-router';
import {useUserStore} from '@/models/user';
import {getToken} from '@/utils/auth';
export function permissionGuard(router: Router) {
  /** 路由白名单 */
  const whiteList = ['/login'];
  router.beforeEach((to, from, next) => {
    // console.log('to', to);
    if (getToken()) {
      const userModel = useUserStore();
      if (to.path === '/login') {
        next();
        router.push('/welcome');
      } else if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        if (userModel.roles.length === 0) {
          userModel.getUserInfo();
        }
        next();
      }
    } else {
      // 没有token
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单，直接进入
        next();
      } else {
        next();
        router.push('/login'); // 否则全部重定向到登录页
      }
    }
  });
}
